import { ColumnProps, PostProps, AuthorProps } from './store'

interface Rules {
  format?: string[];
  size?: number;
}

type ErrorType = 'format' | 'size' | null

interface CheckResult {
  isPass: boolean;
  error: ErrorType;
}

// 文件上传前验证函数
export const beforeUploadCheck = (file: File, rules: Rules): CheckResult => {
  const { format, size } = rules
  const isValidateFormat = format ? format.includes(file.type) : true
  const isValidateSize = size ? (file.size / 1024 / 1024) < size : true
  let error: ErrorType = null
  if (!isValidateFormat) {
    error = 'format'
  }
  if (!isValidateSize) {
    error = 'size'
  }
  return {
    isPass: isValidateFormat && isValidateSize,
    error
  }
}

// 处理专栏头像函数
export const addColumnAvatar = (column: ColumnProps, width: number, height: number): void => {
  if (column.avatar) {
    if (column.avatar.url) {
      column.avatar.fitUrl = column.avatar.url + `?x-oss-process=image/resize,m_pad,h_${height},w_${width}`
    }
  } else {
    column.avatar = {
      fitUrl: require('./assets/column.jpg')
    }
  }
}

// 处理文章图片函数
export const addPostImage = (post: PostProps, width: number, height: number): void => {
  if (post.image) {
    if (post.image.url) {
      post.image.fitUrl = post.image.url + `?x-oss-process=image/resize,m_fill,h_${height},w_${width}`
    }
  }
}

// 处理文章头像函数
export const addPostAvatar = (author: AuthorProps, width: number, height: number): void => {
  if (author.avatar) {
    if (author.avatar.url) {
      author.avatar.fitUrl = author.avatar.url + `?x-oss-process=image/resize,m_pad,h_${height},w_${width}`
    }
  } else {
    author.avatar = {
      fitUrl: require('./assets/avatar.jpg')
    }
  }
}

export function arrToObj<T extends { _id?: string }> (arr: T[]): { [key: string]: T; } {
  return arr.reduce((val, item) => {
    if (item._id) {
      val[item._id] = item
    }
    return val
  }, {} as { [key: string]: T })
}

export function objToArr<T> (obj: { [key: string]: T }): T[] {
  return Object.keys(obj).map(key => obj[key])
}
